<template>
  <div class="countCtrl">
    <div class="ctrl" :class="{null: !Count}" @click="reduce">
      <span>-</span>
    </div>
    <div>
      <input type="tel" v-model="Count">
    </div>
    <div class="ctrl" @click="add">
      <span>+</span>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'CountCtrl',
    props: {
      index: {
        type: Number,
        default: null
      },
      count: Number,
      maxCount: Number
    },
    data() {
      return {
        Count: this.count,
        type:null,
      }
    },
    watch: {
      maxCount: {
        // immediate: true,
        handler() {
          this.Count = 1
        }
      },
      Count: {
        handler(val) {
          this._countChange(val)
        }
      }
    },
    methods: {
      add() {
        this.Count < this.maxCount && this.Count++
        this.type = 'add'
      },
      reduce() {
        this.Count > 1 && this.Count--
        this.type = 'reduce'
      },
      _countChange(val) {
        if(this.Count == 0) {
          this.Count = 1
        }
        if(isNaN(val)) {
          this.Count = 1
          this.$toast('请输入合法数字')
        }
        if(val > this.maxCount) {
          this.Count = this.maxCount
          this.$toast('数量超出范围~')
        }
        this._change()
      },
      _change() {
        this.$emit('change', {
          index: this.index,
          count: Number(this.Count),
          type:this.type,
          stock: this.maxCount
        })
      }
    }
  }
</script>

<style lang="scss">
  @import '@/assets/css/base.scss';
  .countCtrl {
    display: flex;
    height: 0.5rem;
    align-items: center;
    text-align: center;
    .ctrl {
      background: $bgGray;
      &.null {
        background: #F7F7F7;
      }
    }
    div {
      position: relative;
      flex: 0 0 0.5rem;
      width: 0.5rem;
      height: 100%;
      border: 1px solid $colorGray;
      color: #999999;
      input {
        position: absolute;
        @include center;
        width: 100%;
        height:0.4rem;
        text-align: center;
        outline: none;
      }
      span {
        position: absolute;
        @include center;
      }
    }
    div:nth-child(2){
      border-left: 0;
      border-right: 0;
    }
  }
</style>
